#!/bin/bash
set +e

. ./comm.sh

OS_TYPE=""
OS_VERSION=""
WORKING_DIR=$(realpath $(dirname $0))
DOWNLOAD_DIR=""
DOWNLOAD_DIR_MW=$WORKING_DIR/gala_deploy_middleware
DOWNLOAD_DIR_OPS=$WORKING_DIR/gala_deploy_ops
DOWNLOAD_DIR_GRAFANA=$WORKING_DIR/gala_deploy_grafana
DOWNLOAD_DIR_GOPHER=$WORKING_DIR/gala_deploy_gopher
DOCKER_HUB='hub.oepkgs.net'
DOCKER_HUB_TAG_PREFIX="${DOCKER_HUB}/a-ops"
DOWNLOAD_COMPONENT_LIST=""
REMOTE_REPO_PREFIX=""
REMOTE_ALIYUN_REPO_PREFIX="http://mirrors.aliyun.com/openeuler"
EPOL_REPO=""
EPOL_UPDATE_REPO=""

function echo_err_exit() {
    echo -e "\e[31m $@ \e[0m"
    exit 1;
}

function echo_info() {
    echo -e "\e[32m $@ \e[0m"
}

function echo_warn() {
    echo -e "\e[33m $@ \e[0m"
}


function gala_wget() {
    url=$1
    dst_dir=$2
    wget_file=""

    if [ "x$dst_dir" == "x" ] ; then
        dst_dir="./"
    fi
    wget_file=$(echo ${url##*/})
    if [ -f $dst_dir/$wget_file ] ; then
        return;
    fi

    wget $url -P $dst_dir --no-check-certificate
    [ $? -ne 0 ] && echo_err_exit "Error: fail to download $wget_file"
}

function install_rpm() {
    rpm="$1"
    repo_path=""

    if rpm -qa | grep -q $rpm 2>/dev/null ; then
        return
    fi

    if echo $REMOTE_REPO_PREFIX | grep -q "openEuler-22.03-LTS-SP1" ; then
        EPOL_REPO=$REMOTE_REPO_PREFIX/EPOL/main/${OS_ARCH}
        EPOL_UPDATE_REPO=$REMOTE_REPO_PREFIX/EPOL/update/main/${OS_ARCH}
    else
        EPOL_REPO=$REMOTE_REPO_PREFIX/EPOL/${OS_ARCH}
        EPOL_UPDATE_REPO=$REMOTE_REPO_PREFIX/EPOL/update/${OS_ARCH}
    fi

    repo_path="--repofrompath=epol_deploy,$EPOL_REPO \
        --repofrompath=epol_update_deploy,$EPOL_UPDATE_REPO \
        --repofrompath=everything_deploy,$REMOTE_REPO_PREFIX/everything/${OS_ARCH} \
        --repofrompath=update_deploy,$REMOTE_REPO_PREFIX/update/${OS_ARCH}"

    echo $repo_path
    yum install -y  $rpm $repo_path --nogpgcheck
    [ $? -ne 0 ] && echo_err_exit "Error: failed to install $rpm, please check repo!"
}

download_ops_image() {
    echo_info "- Download gala-anteater docker image"
    if [ ! -f ${DOWNLOAD_DIR}/gala-anteater-${OS_ARCH}.tar ] ; then
        echo  "   [1] Executing \"docker pull ${DOCKER_HUB_TAG_PREFIX}/gala-anteater-${OS_ARCH}\""
        docker_pull_image "gala-anteater-${OS_ARCH}:latest"

        echo  "   [2] Executing \"docker save -o ${DOWNLOAD_DIR}/gala-anteater-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/gala-anteater-${OS_ARCH}:latest\""
        docker save -o ${DOWNLOAD_DIR}/gala-anteater-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/gala-anteater-${OS_ARCH}:latest
    fi

    echo_info "- Download gala-spider docker image"
    if [ ! -f ${DOWNLOAD_DIR}/gala-spider-${OS_ARCH}.tar ] ; then
        echo  "   [1] Executing \"docker pull ${DOCKER_HUB_TAG_PREFIX}/gala-spider-${OS_ARCH}\""
        docker_pull_image "gala-spider-${OS_ARCH}:1.0.1"

        echo  "   [2] Executing \"docker save -o ${DOWNLOAD_DIR}/gala-spider-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/gala-spider-${OS_ARCH}:1.0.1\""
        docker save -o ${DOWNLOAD_DIR}/gala-spider-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/gala-spider-${OS_ARCH}:1.0.1
    fi

    echo_info "- Download gala-inference docker image"
    if [ ! -f ${DOWNLOAD_DIR}/gala-inference-${OS_ARCH}.tar ] ; then
        echo  "   [1] Executing \"docker pull ${DOCKER_HUB_TAG_PREFIX}/gala-inference-${OS_ARCH}\""
        docker_pull_image "gala-inference-${OS_ARCH}:1.0.1"

        echo  "   [2] Executing \"docker save -o ${DOWNLOAD_DIR}/gala-inference-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/gala-inference-${OS_ARCH}:1.0.1\""
        docker save -o ${DOWNLOAD_DIR}/gala-inference-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/gala-inference-${OS_ARCH}:1.0.1
    fi

    wget https://gitee.com/openeuler/gala-anteater/raw/master/config/gala-anteater.yaml -O ${DOWNLOAD_DIR}/gala-anteater.yaml --no-check-certificate
}

download_kafka_tarball() {
    KAFKA_VERSION='kafka_2.13-2.8.2'
    echo_info "- Download $KAFKA_VERSION tarball"
    if [ ! -f ${DOWNLOAD_DIR}/${KAFKA_VERSION}.tgz ] ; then
        echo "   Executing \"wget https://mirrors.huaweicloud.com/apache/kafka/2.8.2/${KAFKA_VERSION}.tgz\""
        wget https://mirrors.huaweicloud.com/apache/kafka/2.8.2/${KAFKA_VERSION}.tgz -P ${DOWNLOAD_DIR} --no-check-certificate
    fi

    if ! ls ${DOWNLOAD_DIR} | grep -q java-1.8.0-openjdk ; then
        yum_download java-1.8.0-openjdk
        install_rpm createrepo
        createrepo ${DOWNLOAD_DIR}
    fi
}

download_prometheus() {
    echo_info "- Download prometheus2 rpm"
    if [ ! -f ${DOWNLOAD_DIR}/prometheus2*.${OS_ARCH}.rpm ] ; then
        echo "   Executing \"yumdownloader prometheus2\""
        yum_download prometheus2
    fi
}

download_es_logstash() {
    echo_info "- Download elasticsearch(8.5.3) tarball"
    if [ ! -f ${DOWNLOAD_DIR}/elasticsearch-8.5.3-linux-${OS_ARCH}.tar.gz ] ; then
        echo "    Executing \"wget https://mirrors.huaweicloud.com/elasticsearch/8.5.3/elasticsearch-8.5.3-linux-${OS_ARCH}.tar.gz\""
        wget https://mirrors.huaweicloud.com/elasticsearch/8.5.3/elasticsearch-8.5.3-linux-${OS_ARCH}.tar.gz -P ${DOWNLOAD_DIR} --no-check-certificate
    fi

    echo_info "- Download logstash(8.5.3) tarball"
    if [ ! -f ${DOWNLOAD_DIR}/logstash-8.5.3-${OS_ARCH}.rpm ] ; then
        echo "    Executing \"wget https://mirrors.huaweicloud.com/logstash/8.5.3/logstash-8.5.3-linux-${OS_ARCH}.tar.gz\""
        wget https://mirrors.huaweicloud.com/logstash/8.5.3/logstash-8.5.3-linux-${OS_ARCH}.tar.gz  -P ${DOWNLOAD_DIR} --no-check-certificate
    fi
}

download_arangodb_image() {
    echo_info "- Download arangodb docker image"
    if [ ! -f ${DOWNLOAD_DIR}/arangodb-${OS_ARCH}.tar ] ; then
        echo  "   [1] Executing \"docker pull ${DOCKER_HUB_TAG_PREFIX}/arangodb-${OS_ARCH}\""
        docker_pull_image "arangodb-${OS_ARCH}"

        echo  "   [2] Executing \"docker save -o ${DOWNLOAD_DIR}/arangodb-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/arangodb-${OS_ARCH}\""
        docker save -o ${DOWNLOAD_DIR}/arangodb-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/arangodb-${OS_ARCH}
    fi
}

download_pyroscope() {
    echo_info "- Download pyroscope rpm"
    if [ ! -f ${DOWNLOAD_DIR}/pyroscope-0.37.2-1-${OS_ARCH}.rpm ] ; then
        echo "   Executing \"wget https://dl.pyroscope.io/release/pyroscope-0.37.2-1-${OS_ARCH}.rpm\""
        wget https://dl.pyroscope.io/release/pyroscope-0.37.2-1-${OS_ARCH}.rpm -P ${DOWNLOAD_DIR} --no-check-certificate
    fi
}


download_grafana_image() {
    echo_info "- Download grafana docker image"
    if [ ! -f ${DOWNLOAD_DIR}/grafana-${OS_ARCH}.tar ] ; then
        echo  "   [1] Executing \"docker pull ${DOCKER_HUB_TAG_PREFIX}/grafana-${OS_ARCH}:latest\""
        docker_pull_image "grafana-${OS_ARCH}"

        echo  "   [2] Executing \"docker save -o ${DOWNLOAD_DIR}/grafana-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/grafana-${OS_ARCH}\""
        docker save -o ${DOWNLOAD_DIR}/grafana-${OS_ARCH}.tar ${DOCKER_HUB_TAG_PREFIX}/grafana-${OS_ARCH}
    fi

    echo_info "- Download python dep for arangodb2es.py"
    if ! which pip3 >/dev/null ; then
        install_rpm python3-pip
    fi
    pip3 download elasticsearch python-arango pytz pyArango \
        -d ${DOWNLOAD_DIR} -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com
    yum_download python3-pip

    yum_download jq

    install_rpm createrepo
    createrepo ${DOWNLOAD_DIR}

    echo_info "- Download grafana dashboard json file"
    download_grafana_dashboard ${DOWNLOAD_DIR}
}

# get gopher image tag by os_version
get_gopher_image_tag() {
    if [ "x$OS_TYPE" == "xopenEuler" ] ; then
        if [ "$OS_VERSION" == "openEuler-22.03-LTS-SP1" ] ; then
            echo "22.03-lts-sp1"
        elif [ "$OS_VERSION" == "openEuler-22.03-LTS" ] ; then
            echo "22.03-lts"
        else #openEuler-20.03-LTS-SP1
            echo "20.03-lts-sp1"
        fi
    else
        echo "${OS_VERSION}"
    fi
}

download_gopher_image() {
    tag=$(get_gopher_image_tag)
    echo_info "- Download  gala-gopher docker image"
    if [ ! -f ${DOWNLOAD_DIR}/gala-gopher-${OS_ARCH}-${tag}.tar ] ; then
        echo  "   [1] Executing \"docker pull ${DOCKER_HUB_TAG_PREFIX}/gala-gopher-${OS_ARCH}:${tag}\""
        docker_pull_image "gala-gopher-${OS_ARCH}:${tag}"

        echo  "   [2] Executing \"docker save -o ${DOWNLOAD_DIR}/gala-gopher-${OS_ARCH}:${tag}.tar ${DOCKER_HUB_TAG_PREFIX}/gala-gopher-${OS_ARCH}:${tag}\""
        docker save -o ${DOWNLOAD_DIR}/gala-gopher-${OS_ARCH}:${tag}.tar ${DOCKER_HUB_TAG_PREFIX}/gala-gopher-${OS_ARCH}:${tag}
    fi

    gala_wget https://gitee.com/openeuler/gala-gopher/raw/dev/k8s/daemonset.yaml.tmpl ${DOWNLOAD_DIR}
}

# use OS_TYPE OS_VERSION config yum repo
function config_remote_repo() {
    [ "x$OS_VERSION" == "x" ] && echo_err_exit "Unsupport OS version, aborting"

    if [ "x$OS_TYPE" == "xopenEuler" ] ; then
        if [ "$OS_VERSION" == "openEuler-22.03-LTS-SP1" ] ; then
            REMOTE_REPO_PREFIX="$REMOTE_ALIYUN_REPO_PREFIX/$OS_VERSION"
        elif [ "$OS_VERSION" == "openEuler-22.03-LTS" ] ; then
            REMOTE_REPO_PREFIX="$REMOTE_ALIYUN_REPO_PREFIX/openEuler-22.03-LTS-SP1"
        elif [ "$OS_VERSION" == "openEuler-20.03-LTS-SP1" ] ; then
            REMOTE_REPO_PREFIX="$REMOTE_ALIYUN_REPO_PREFIX/$OS_VERSION"
        else
            echo_err_exit "Unsupported openEuler version, aborting!"
        fi
    elif [ "x$OS_TYPE" == "xkylin" ] ; then
        [ ${OS_ARCH} != "x86_64" ] && echo_err_exit "Unsupported on Kylin aarch64"
        if [ "$OS_VERSION" == "kylin-v10-sp1" ] ; then
            REMOTE_REPO_PREFIX="$REMOTE_ALIYUN_REPO_PREFIX/openEuler-20.03-LTS-SP1"
        elif [ "$OS_VERSION" == "kylin-v10-sp3" ] ; then
            REMOTE_REPO_PREFIX="$REMOTE_ALIYUN_REPO_PREFIX/openEuler-22.03-LTS-SP3"
        else
            echo_err_exit "Unsupported Kylin version, aborting!"
        fi
    elif [ "x$OS_TYPE" == "xeuleros" ] ; then
        REMOTE_REPO_PREFIX="$REMOTE_ALIYUN_REPO_PREFIX/openEuler-20.03-LTS-SP1"
    else
        echo_err_exit "Unsupport OS type, aborting"
    fi
}

function detect_os() {
    OS_TYPE=$(cat /etc/os-release | grep '^ID=' | awk -F '\"' '{print $2}')
    [ -z "$OS_TYPE" ] && echo_err_exit "Unsupport OS type, aborting!"

    if [ "x$OS_TYPE" == "xopenEuler" ] ; then
        OS_VERSION=$(cat /etc/openEuler-latest | head -n1 | awk -F= '{print $2}')
    elif [ "x$OS_TYPE" == "xkylin" ] ; then
        kylin_milestone=$(cat /etc/.kyinfo | grep '^milestone=' | awk -F "=" '{print $2}')
        if [[ "$kylin_milestone" =~ "10-SP1" ]] ; then
            OS_VERSION="kylin-v10-sp1"
        elif [[ "$kylin_milestone" =~ "10-SP3" ]] ; then
            OS_VERSION="kylin-v10-sp3"
        fi
    elif [ "x$OS_TYPE" == "xeuleros" ] ; then
        eulerversion=$(cat /etc/euleros-latest | grep '^eulerversion=' | awk -F "=" '{print $2}')
        if [[ "$eulerversion" =~ "V200R008" ]] ; then
            OS_VERSION="euleros-v2r8"
        elif [[ "$eulerversion" =~ "V200R009" ]] ; then
            OS_VERSION="euleros-v2r9"
        elif [[ "$eulerversion" =~ "V200R010" ]] ; then
            OS_VERSION="euleros-v2r10"
        fi
    fi
}

function config_os_version_type() {
    os_version="$1"
    os_arch="${2:-$(uname -m)}"

    if [[ $os_version =~ "kylin" ]] ; then
        OS_TYPE="kylin"
    elif [[ $os_version =~ "openEuler" ]] ; then
        OS_TYPE="openEuler"
    elif [[ $os_version =~ "euleros" ]] ; then
        OS_TYPE="euleros"
    else
        echo_err_exit "Unsupport OS type, aborting"
    fi

    OS_VERSION=$os_version

    if [ $os_arch == "aarch64" ] || [ $os_arch == "x86_64" ]; then
        OS_ARCH=$os_arch
    else
        echo_err_exit "no support \"$os_arch\" arch"
    fi
}

function parse_arg_gopher() {
    if [ $# -gt 3 ];then
        echo_err_exit "download gopher param err"
    fi

    config_os_version_type $2 $3
}

function parse_arch() {
    if [ $# -eq 1 ] ; then
        return;
    fi

    if [ $# -ne 2 ] ; then
        echo_err_exit "download param err"
    fi

    if [ $2 == "aarch64" ] || [ $2 == "x86_64" ]; then
        OS_ARCH=$2
    else
        echo_err_exit "invalid arch:\"$2\" , must be aarch64 or x86_64"
    fi
}

detect_os
component=$1
case "x$component" in
    xgopher)
        DOWNLOAD_COMPONENT_LIST="${DOWNLOAD_COMPONENT_LIST}gopher "
        DOWNLOAD_DIR=$DOWNLOAD_DIR_GOPHER
        if [ $# -gt 1 ]; then
            parse_arg_gopher $@
        fi
        ;;
    xops)
        DOWNLOAD_COMPONENT_LIST="${DOWNLOAD_COMPONENT_LIST}ops "
        DOWNLOAD_DIR=$DOWNLOAD_DIR_OPS
        parse_arch $@
        ;;
    xmiddleware)
        DOWNLOAD_COMPONENT_LIST="${DOWNLOAD_COMPONENT_LIST}middleware "
        DOWNLOAD_DIR=$DOWNLOAD_DIR_MW
        parse_arch $@
        ;;
    xgrafana)
        DOWNLOAD_COMPONENT_LIST="${DOWNLOAD_COMPONENT_LIST}grafana "
        DOWNLOAD_DIR=$DOWNLOAD_DIR_GRAFANA
        parse_arch $@
        ;;
    x)
        echo_err_exit "Must specify download component"
        ;;
    *)
        echo_err_exit "Unsupport component:" $component
        ;;
esac


config_remote_repo
mkdir -p ${DOWNLOAD_DIR}
if [[ "${DOWNLOAD_COMPONENT_LIST}" =~ "middleware" ]] ; then
    download_kafka_tarball
    download_prometheus
    download_es_logstash
    download_arangodb_image
    download_pyroscope
fi

if [[ "${DOWNLOAD_COMPONENT_LIST}" =~ "grafana" ]]  ; then
    download_grafana_image
    download_gala_web_rpm ${DOWNLOAD_DIR}
fi

if [[ "${DOWNLOAD_COMPONENT_LIST}" =~ "ops" ]]  ; then
    download_ops_image
fi

if [[ "${DOWNLOAD_COMPONENT_LIST}" =~ "gopher" ]]  ; then
    download_gopher_image
fi
